package org.jeecg.modules.hc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 企业商户关系表
 * @Author: jeecg-boot
 * @Date:   2023-07-04
 * @Version: V1.0
 */
@Api(tags="企业商户关系表")
@RestController
@RequestMapping("/hc/hcCompanyMerchantInfo")
@Slf4j
public class HcCompanyMerchantInfoController extends JeecgController<HcCompanyMerchantInfo, IHcCompanyMerchantInfoService> {
	@Autowired
	private IHcCompanyMerchantInfoService hcCompanyMerchantInfoService;
	@Autowired
	private IHcCompanyFoodListService hcCompanyFoodListService;
	@Autowired
	private IHcMerchantService merchantService;
	@Autowired
	private IHcCompanyDetailService companyDetailService;
	@Autowired
	private IHcCompanyFoodDisplayService companyFoodDisplayService;


	/**
	 * 商户查询绑定的企业
	 */
	@ApiOperation(value="商户查询绑定的企业", notes="商户查询绑定的企业")
	@GetMapping(value = "/queryCompanyListByMerchantId")
	public Result<?> queryCompanyListByMerchantId(@RequestParam(name = "merchantId")String merchantId) {
		return Result.OK(hcCompanyMerchantInfoService.queryCompanyListByMerchantId(merchantId));
	}


	 /**
	  *   添加
	  * @return
	  */
	 @AutoLog(value = "企业商户关系表-添加")
	 @ApiOperation(value="企业商户关系表-添加", notes="企业商户关系表-添加")
	 //@RequiresPermissions("org.jeecg.modules:hc_company_merchant_info:add")
	 @GetMapping(value = "/addMerchantInfo")
	 public Result<String> addMerchantInfo(@RequestParam(name = "companyId")String companyId,
										   @RequestParam(name = "merchantIds")String merchantIds,
										   @RequestParam(name = "menuDisplayTime")String menuDisplayTime) {
	 	 LambdaQueryWrapper<HcCompanyDetail> companyDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
		 companyDetailLambdaQueryWrapper.eq(HcCompanyDetail::getCompanyId,companyId);
		 List<HcCompanyDetail> list = companyDetailService.list(companyDetailLambdaQueryWrapper);
		 companyDetailLambdaQueryWrapper.eq(HcCompanyDetail::getMenuDisplayTime,menuDisplayTime).last("limit 1");
		 HcCompanyDetail one = companyDetailService.getOne(companyDetailLambdaQueryWrapper);
		 if (null!=one){
		 	throw new JeecgBootException("已创建当日菜单，无需再次创建");
		 }
		 if (CollectionUtils.isNotEmpty(list)){
		 	LambdaQueryWrapper<HcCompanyMerchantInfo> companyMerchantInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
			 companyMerchantInfoLambdaQueryWrapper.eq(HcCompanyMerchantInfo::getCompanyId,companyId);
			 hcCompanyMerchantInfoService.remove(companyMerchantInfoLambdaQueryWrapper);
		 }

		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
	 	 //添加关系
		 List<String> merchantIdList = Arrays.asList(merchantIds.split(","));
		 List<String> merchantNames = new ArrayList<>();

		 String detailsId = UuidUtils.getUUID();
		 //添加企业和商户的关系
		 merchantIdList.forEach(m -> {
		 	HcCompanyMerchantInfo hcCompanyMerchantInfo = new HcCompanyMerchantInfo();
			 hcCompanyMerchantInfo.setCompanyId(companyId);
			 hcCompanyMerchantInfo.setMerchantId(m);
			 hcCompanyMerchantInfoService.save(hcCompanyMerchantInfo);

			 LambdaQueryWrapper<HcMerchant> merchantLambdaQueryWrapper = new LambdaQueryWrapper<>();
			 merchantLambdaQueryWrapper.eq(HcMerchant::getId,m).last("limit 1");
			 HcMerchant hcMerchant = merchantService.getOne(merchantLambdaQueryWrapper);
			 merchantNames.add(hcMerchant.getStoreName());

			 //根据企业和商户id获取对应的菜品库的菜品
			 List<String> ids = hcCompanyFoodListService.list(new LambdaQueryWrapper<HcCompanyFoodList>()
					 .eq(HcCompanyFoodList::getCompanyId, companyId)
					 .eq(HcCompanyFoodList::getMerchantId, m))
					 .stream().map(HcCompanyFoodList::getId).collect(Collectors.toList());

			 //将菜品库自动添加到展示库
			 ids.forEach(c-> {
				 HcCompanyFoodDisplay companyFoodDisplay = new HcCompanyFoodDisplay();
				 companyFoodDisplay.setCompanyDetailId(detailsId);
				 companyFoodDisplay.setMerchantId(m);
				 companyFoodDisplay.setCompanyId(companyId);
				 companyFoodDisplay.setFoodsListId(c);
				 companyFoodDisplayService.save(companyFoodDisplay);
			 });

		 });
		 //添加企业商户详情
		 String merchantName = Joiner.on(";").join(merchantNames);
		 HcCompanyDetail hcCompanyDetail = new HcCompanyDetail();
		 hcCompanyDetail.setId(detailsId);
		 hcCompanyDetail.setCompanyId(companyId);
		 hcCompanyDetail.setListingStoreIds(merchantIds);
		 hcCompanyDetail.setListingStore(merchantName);
		 hcCompanyDetail.setCreateTime(DateUtils.getDate());
		 hcCompanyDetail.setCreateBy(sysUser.getRealname());
		 hcCompanyDetail.setMenuDisplayTime(menuDisplayTime);
		 companyDetailService.save(hcCompanyDetail);
		 return Result.OK("添加成功！");
	 }

	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyMerchantInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "企业商户关系表-分页列表查询")
	@ApiOperation(value="企业商户关系表-分页列表查询", notes="企业商户关系表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<HcCompanyMerchantInfo>> queryPageList(HcCompanyMerchantInfo hcCompanyMerchantInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HcCompanyMerchantInfo> queryWrapper = QueryGenerator.initQueryWrapper(hcCompanyMerchantInfo, req.getParameterMap());
		Page<HcCompanyMerchantInfo> page = new Page<HcCompanyMerchantInfo>(pageNo, pageSize);
		IPage<HcCompanyMerchantInfo> pageList = hcCompanyMerchantInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hcCompanyMerchantInfo
	 * @return
	 */
//	@AutoLog(value = "企业商户关系表-添加")
//	@ApiOperation(value="企业商户关系表-添加", notes="企业商户关系表-添加")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody HcCompanyMerchantInfo hcCompanyMerchantInfo) {
		hcCompanyMerchantInfoService.save(hcCompanyMerchantInfo);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hcCompanyMerchantInfo
	 * @return
	 */
	@AutoLog(value = "企业商户关系表-编辑")
	@ApiOperation(value="企业商户关系表-编辑", notes="企业商户关系表-编辑")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HcCompanyMerchantInfo hcCompanyMerchantInfo) {
		hcCompanyMerchantInfoService.updateById(hcCompanyMerchantInfo);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业商户关系表-通过id删除")
	@ApiOperation(value="企业商户关系表-通过id删除", notes="企业商户关系表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hcCompanyMerchantInfoService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业商户关系表-批量删除")
	@ApiOperation(value="企业商户关系表-批量删除", notes="企业商户关系表-批量删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hcCompanyMerchantInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "企业商户关系表-通过id查询")
	@ApiOperation(value="企业商户关系表-通过id查询", notes="企业商户关系表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HcCompanyMerchantInfo> queryById(@RequestParam(name="id",required=true) String id) {
		HcCompanyMerchantInfo hcCompanyMerchantInfo = hcCompanyMerchantInfoService.getById(id);
		if(hcCompanyMerchantInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hcCompanyMerchantInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hcCompanyMerchantInfo
    */
    //@RequiresPermissions("org.jeecg.modules:hc_company_merchant_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcCompanyMerchantInfo hcCompanyMerchantInfo) {
        return super.exportXls(request, hcCompanyMerchantInfo, HcCompanyMerchantInfo.class, "企业商户关系表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("hc_company_merchant_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcCompanyMerchantInfo.class);
    }

}
